const http = require('http')
const createHandler = require('./node-gitee-webhook/index')
const exec = require('child_process').exec
const request = require('request-promise');

function execFunc(content) {
    return new Promise((resolve, reject) => {
        exec(content, function (error, stdout, stderr) {
            if (error) {
                reject(error)
            }

            resolve({ stdout, stderr })
        })
    })
}

let handler = createHandler([ // 多个仓库
    { path: '/eslint', secret: 'eslint' }
])
// var handler = createHandler({ path: '/webhook1', secret: 'secret1' }) // 单个仓库

http.createServer(function (req, res) {
    handler(req, res, function (err) {
        if (err) {
            console.log(err)
        }
        res.statusCode = 404
        res.end('no such location')
    })
}).listen(3000)

handler.on('error', function (err) {
    console.error('Error:', err.message)
})

handler.on('Push Hook', function (data) {
    console.log(
        'Received a push data for %s to %s',
        data.payload.repository.name,
        data.payload.ref
    )
    // console.log(data)
    execFunc('sh webhook.sh ' + data.payload.repository.url).then(({ stdout, stderr }) => {
        console.log('stdout:' + stdout)
        sendMessage(true, data.payload.repository.url).then(res => {
            console.log(res)
        })
    }).catch((err) => {
        console.log(err)
        console.log('脚本执行失败')
        sendMessage(false, data.payload.repository.url).then(res => {
            console.log(res)
        })
    })
})

function sendMessage(isSuccess, url) {
    let text = isSuccess ? `eslint 校验成功\ngit仓库为：${url}` : `【请注意】eslint 校验失败\ngit仓库为：${url}\n`

    return request({
        method: 'POST',
        uri: 'https://oapi.dingtalk.com/robot/send?access_token=cf629fe03a25ebb16d37228ccd52ae132efd41425b8ca6aa8de208a0f8941abd',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            'msgtype': 'text',
            'text': { content: text },
            'at': { isAtAll: !isSuccess }
        })
    })
}